class_name SaveData
extends Resource


@export var last_score := 0
#@export var inventory: Resource = Inventory.new()
@export var level_name := ""

@export var level_highscores := []


const SAVE_SCORE_PATH := "user://save"

func save_score_data():
	print (level_name)
	
	update_highscore_entry()
		
	
	ResourceSaver.save(self, SaveData.get_save_path())

static func save_exists() -> bool:
	return ResourceLoader.exists(get_save_path())
	


static func load_score_data() -> Resource:
	var save_path := get_save_path()
	

	return ResourceLoader.load(save_path)


	


static func get_save_path() -> String:
	var extension := ".tres" if OS.is_debug_build() else ".res"
	return SAVE_SCORE_PATH + extension

func update_highscore_entry():
	if level_name == "":
		return
	if highscore_entry_exists(level_name):
		if last_score > get_highscore_entry(level_name):
			print ("highscore in level")
			overwrite_highscore_entry(level_name, last_score)
		else:
			print ("no highscore")
		#print ("entry found: " + str(get_highscore_entry_index(level_name)))
		#print ("entry found: " + str(get_highscore_entry_index(level_name)))
		return
	print ("creating new highscore entry for level: " + str(level_name) + ", value: " + str(last_score))
	var _temp_score := []
	_temp_score.append(level_name)
	_temp_score.append(last_score)
	level_highscores.append(_temp_score)
	
func highscore_entry_exists(_level_name):
	for hs in level_highscores:
		if hs[0] == _level_name:
			return true
	return false
			
func get_highscore_entry_index(_level_name):
	var _index = 0
	for hs in level_highscores:
		if hs[0] == _level_name:
			return _index
		_index +=1
		

func get_highscore_entry(_level_name):
	if _level_name == null:
		return
	for hs in level_highscores:
		if hs[0] == _level_name:
			print ("returning level highscore..")
			return hs[1]
	print ("ERROR: returning nothing!!!")		
	return -1
	
func overwrite_highscore_entry(_level_name, value):
	for hs in level_highscores:
		if hs[0] == _level_name:
			level_highscores[get_highscore_entry_index(_level_name)][1] = value
	print (level_highscores)
	
